package com.sgb.kjwl.view.ui.fragment.machine;

import androidx.databinding.DataBindingUtil;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentMyAskLeaseBinding;
import com.sgb.kjwl.di.machine.DaggerMachineFragComponent;
import com.sgb.kjwl.di.machine.MachineFragModule;
import com.sgb.kjwl.model.entity.self.LeaseAskStateEntity;
import com.sgb.kjwl.model.entity.self.LeaseStateEntity;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.lease.AskLeaseItemEntity;
import com.sgb.kjwl.view.event.AskLeaseLookEvent;
import com.sgb.kjwl.model.entity.lease.AskLeaseSheBeiEntity2;
import com.sgb.kjwl.view.ui.adapter.machine.MyAskLeaseAdapter;
import com.sgb.kjwl.view.widget.lease.LeaseAskMapPopWindow;
import com.sgb.kjwl.viewmodel.machine.MyAskLeaseFragModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

public class MyAskLeaseFragment extends AppLazyFragment {

    private FragmentMyAskLeaseBinding binding;

    private String classNo = "";
    private String statusNo = "";

    private LeaseAskMapPopWindow classPopWindow;
    private LeaseAskMapPopWindow typePopWindow;

    private int page = 1;
    private boolean isLoadMore = false;
    private MyAskLeaseAdapter askLeaseAdapter;
    private String categoryType = "";
    private ArrayList<AskLeaseItemEntity<List<AskLeaseItemEntity>>> allDatas;
    private List<PickSelectEntity> classDatas;
    private List<PickSelectEntity> statusDatas;

    @Inject
    MyAskLeaseFragModel askLeaseFragModel;

    public static MyAskLeaseFragment newInstance(String categoryType, int position, ArrayList<AskLeaseItemEntity<List<AskLeaseItemEntity>>> list) {
        MyAskLeaseFragment fragment = new MyAskLeaseFragment();
        Bundle bundle = new Bundle();
        bundle.putString("categoryType", categoryType);
        bundle.putSerializable("data", list);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMachineFragComponent.builder()
                .appComponent(appComponent)
                .machineFragModule(new MachineFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_my_ask_lease, container, false);
        return binding.getRoot();
    }

    @Override
    protected void onLazyLoad() {
        categoryType = getArguments().getString("categoryType");
        allDatas = (ArrayList<AskLeaseItemEntity<List<AskLeaseItemEntity>>>) getArguments().getSerializable("data");
        if ("2".equals(categoryType)) {
            binding.tvClass.setText("车型");
        }
        initData();
        getData();
    }

    @Override
    protected void initView() {
        binding.classLayout.setOnClickListener(this);
        binding.typeLayout.setOnClickListener(this);
        if (askLeaseAdapter == null) {
            askLeaseAdapter = new MyAskLeaseAdapter(getActivity(), null);
        }
        binding.recyclerView.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0,
                getActivity().getResources().getDimension(R.dimen.dp1),
                getActivity().getResources().getColor(R.color.color_F5F5F5)));
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setAdapter(askLeaseAdapter);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                isLoadMore = false;
                page = 1;
                getData();
            }

            @Override
            public void onLoadMore() {
                isLoadMore = true;
                page = page + 1;
                getData();
            }
        });
//
//        askLeaseAdapter.setOnItemClick(new AdapterOnItemClick2<AskLeaseSheBeiEntity2>() {
//            @Override
//            public void onItemClick(AskLeaseSheBeiEntity2 tenderListEntity, int p) {
////                MyAskLeaseQutedListActivity.start(getActivity(),tenderListEntity.getId());
//                askLeaseFragModel.getH5Url(tenderListEntity.getCategoryType(), tenderListEntity.getId());
//                AskLeaseLookEvent askLeaseLookEvent = new AskLeaseLookEvent();
//                askLeaseLookEvent.setId(tenderListEntity.getId());
//                askLeaseLookEvent.setType("my_ask_lease_price");
//                binding.recyclerView.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        EventBus.getDefault().postSticky(askLeaseLookEvent);
//                    }
//                }, 1000);
//            }
//        });


        askLeaseAdapter.setOnCallBlackListener(new MyAskLeaseAdapter.OnCallBlackListener() {
            @Override
            public void onRefresh() {
                isLoadMore = false;
                page = 1;
                getData();
            }

            @Override
            public void onDetail(String categoryType, String id) {
                askLeaseFragModel.getH5Url(Integer.parseInt(categoryType), id);
//                AskLeaseLookEvent askLeaseLookEvent = new AskLeaseLookEvent();
//                askLeaseLookEvent.setId(id);
//                askLeaseLookEvent.setType(categoryType);
//                binding.recyclerView.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        EventBus.getDefault().postSticky(askLeaseLookEvent);
//                    }
//                }, 1000);
            }
        });

        classPopWindow = new LeaseAskMapPopWindow(getActivity());
//        classPopWindow.setBgView();
        classPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                classNo = ((PickSelectEntity) type).getNo();
                binding.tvClass.setText(((PickSelectEntity) type).getProjectscale());
                isLoadMore = false;
                page = 1;
                getData();
            }
        });
        classPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                binding.classArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
            }
        });

        typePopWindow = new LeaseAskMapPopWindow(getActivity());
        typePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                statusNo = ((PickSelectEntity) type).getNo();
                binding.tvType.setText(((PickSelectEntity) type).getProjectscale());
                isLoadMore = false;
                page = 1;
                getData();
            }
        });
        typePopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                binding.typeArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
            }
        });

    }

    private void initData() {
        classDatas = new ArrayList<>();
        //状态(1:报价中;2:流标;3:报价结束;4:已完成)
        statusDatas = new ArrayList<>();
        statusDatas.add(new PickSelectEntity("", "不限"));
        statusDatas.add(new PickSelectEntity("1", "报价中"));
        statusDatas.add(new PickSelectEntity("3", "报价结束"));
        statusDatas.add(new PickSelectEntity("4", "已完成"));
        initClassData();
    }

    private void initClassData() {
        if ("2".equals(categoryType)) {//车辆求租
            onResetCarByClassData();
        } else {
            for (AskLeaseItemEntity<List<AskLeaseItemEntity>> l : allDatas) {
                PickSelectEntity entity = new PickSelectEntity();
                entity.setNo(l.getNo());
                entity.setProjectscale(l.getName());
                classDatas.add(entity);
            }
        }
        PickSelectEntity entity = new PickSelectEntity();
        entity.setNo("");
        entity.setProjectscale("不限");
        classDatas.add(0, entity);
    }

    //因接口返回Json格式不规范,需要在此特别处理一级数据车型
    private void onResetCarByClassData() {
        classDatas.clear();
        for (AskLeaseItemEntity itemEntity : allDatas.get(0).getChildren()) {
            PickSelectEntity selectEntity = new PickSelectEntity();
            selectEntity.setNo(itemEntity.getNo());
            selectEntity.setProjectscale(itemEntity.getName());
            classDatas.add(selectEntity);
        }
    }

    private void getData() {
        askLeaseFragModel.getDataList(categoryType, classNo, statusNo, page);
    }

    public void showList(List<LeaseAskStateEntity> list) {
        binding.recyclerView.refreshComplete();
        binding.recyclerView.loadMoreComplete();
        if (isLoadMore) {
            if (list.size() > 0) {
                askLeaseAdapter.addDatas(list);
            } else {
                binding.recyclerView.setNoMore(true);
            }
            binding.recyclerView.setVisibility(View.VISIBLE);
        } else {
            if (list.size() > 0) {
                binding.recyclerView.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                askLeaseAdapter.setDatas(list);
                binding.recyclerView.setNoMore(false);
            } else {
                askLeaseAdapter.setDatas(null);
                binding.recyclerView.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.class_layout:
                if (null != classDatas && classDatas.size() > 0) {
                    showClassPop();
                }
                break;
            case R.id.type_layout:
                if (null != statusDatas && statusDatas.size() > 0) {
                    showTypePop();
                }
                break;
        }
    }

    private void showClassPop() {
        binding.classArrowView.setImageResource(R.mipmap.ic_up_arrow_n);
        classPopWindow.showPopwindow(binding.roomLayout, 0, 2);
        classPopWindow.setData(classDatas);
    }

    private void showTypePop() {
        binding.typeArrowView.setImageResource(R.mipmap.ic_up_arrow_n);
        typePopWindow.showPopwindow(binding.roomLayout, 0, 2);
        typePopWindow.setData(statusDatas);
    }
}
